# Maintainer: Fabien Chouteau <chouteau@adacore.com>

_realname=stlink
pkgbase="mingw-w64-${_realname}"
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=1.7.0
pkgrel=2
pkgdesc='Firmware programmer for STM32 STLINK v1/v2 protocol'
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clangarm64' 'clang32')
url='https://github.com/stlink-org/stlink'
license=(BSD)
depends=("${MINGW_PACKAGE_PREFIX}-libusb")
makedepends=("${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-cc")
source=("${_realname}-${pkgver}.tar.gz::https://github.com/stlink-org/stlink/archive/v${pkgver}.tar.gz"
        "0001-cmake-find-libusb.patch")
sha256sums=('57ec1214905aedf59bee7f70ddff02316f64fa9ba5a9b6a3a64952edc5b65855'
            '6b1f278eef5f496c7dfb958089cb65c793b80a52c16c36733803e94c05daa51f')

prepare() {
  cd "${srcdir}/${_realname}-${pkgver}"
  patch -p1 -i "${srcdir}/0001-cmake-find-libusb.patch"
}

build() {
  [[ -d "${srcdir}/build-${MSYSTEM}" ]] && rm -rf "${srcdir}/build-${MSYSTEM}"
  mkdir -p "${srcdir}/build-${MSYSTEM}" && cd "${srcdir}/build-${MSYSTEM}"

  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -GNinja \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    ${_extra_config[@]} \
    ../${_realname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake.exe --build ./
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"

  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake.exe --install .
}
